; ((doc, storage, location) => {
    const oList = doc.querySelector('#list');
    const oMsg = doc.querySelector('#message');
    const oSendBtn = doc.querySelector('#send');
    const ws = new WebSocket('ws:localhost:8000');
    let username = '';

    const init = () => {
        bindEvent();
    }

    function bindEvent() {
        oSendBtn.addEventListener('click', handleSendBtnClick, false);
        ws.addEventListener('open', handleOpen, false);
        ws.addEventListener('close', handleClose, false);
        ws.addEventListener('error', handleError, false);
        ws.addEventListener('message', handleMessage, false);

    }

    function handleSendBtnClick() {
        const msg = oMsg.value;

        if (!msg.trim().length) {
            return;
        }

        ws.send(JSON.stringify({
            user: username,
            dateTime: new Date().getTime(),
            message: msg
        }));

        oMsg.value='';
    }
    function handleOpen(e) {
        console.log('websocked连接', e);

        username = storage.getItem('username');
        if (!username) {
            location.href = 'entry.html';
            return;
        }
    }
    function handleClose(e) {
        console.log('websocked连接关闭', e);
    }
    function handleError(e) {
        console.log('websocked连接错误', e);
    }
    function handleMessage(msg) {

        console.log('websocked收到', msg);

        const reader = new FileReader();
        let result = null;
        if (msg.data instanceof Blob) {
            reader.readAsText(msg.data, "UTF-8");
            reader.onload = (e) => {
                result = JSON.parse(reader.result);
                console.log('websocked收到', result);

                //debugger
                //将消息添加到list中
                oList.appendChild(creatMsg(result));
            }
        }


    }




    function creatMsg(data) {
        //debugger
        const { user, dateTime, message } = data;
        const oItem = doc.createElement('li');
        oItem.innerHTML = `
    <p>
       <span>${user}</span>
       <i>${new Date(dateTime)}</i>
    </p>
    <p>消息：${message}</p>
    `;

        return oItem;
    }

    init();
})(document, localStorage, location);